<template>
  <Teleport to="body">
    <Transition name="apple-modal" appear>
      <div
        v-if="modelValue"
        class="apple-modal-overlay"
        :class="overlayClass"
        @click="handleOverlayClick"
      >
        <div
          class="apple-modal"
          :class="modalClass"
          :style="modalStyle"
          @click.stop
        >
          <!-- 模态框头部 -->
          <div v-if="showHeader" class="apple-modal__header">
            <slot name="header">
              <h3 class="apple-modal__title">{{ title }}</h3>
              <button
                v-if="showClose"
                class="apple-modal__close"
                @click="handleClose"
                :aria-label="closeAriaLabel"
              >
                <svg class="apple-modal__close-icon" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                </svg>
              </button>
            </slot>
          </div>

          <!-- 模态框内容 -->
          <div class="apple-modal__body" :class="bodyClass">
            <slot></slot>
          </div>

          <!-- 模态框底部 -->
          <div v-if="showFooter" class="apple-modal__footer">
            <slot name="footer">
              <AppleButton
                v-if="showCancel"
                variant="secondary"
                @click="handleCancel"
              >
                {{ cancelText }}
              </AppleButton>
              <AppleButton
                v-if="showConfirm"
                :variant="confirmVariant"
                :loading="confirmLoading"
                @click="handleConfirm"
              >
                {{ confirmText }}
              </AppleButton>
            </slot>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { computed, watch, nextTick } from 'vue'
import { useLockScroll } from '../composables/useLockScroll'
import AppleButton from './AppleButton.vue'

export interface AppleModalProps {
  modelValue: boolean
  title?: string
  width?: string | number
  maxWidth?: string | number
  height?: string | number
  maxHeight?: string | number
  variant?: 'default' | 'compact' | 'fullscreen' | 'drawer'
  position?: 'center' | 'top' | 'bottom'
  showHeader?: boolean
  showFooter?: boolean
  showClose?: boolean
  showCancel?: boolean
  showConfirm?: boolean
  cancelText?: string
  confirmText?: string
  confirmVariant?: 'primary' | 'success' | 'warning' | 'danger'
  confirmLoading?: boolean
  closeOnOverlay?: boolean
  closeOnEscape?: boolean
  lockScroll?: boolean
  destroyOnClose?: boolean
  customClass?: string
  overlayClass?: string
  bodyClass?: string
  closeAriaLabel?: string
}

const props = withDefaults(defineProps<AppleModalProps>(), {
  title: '',
  width: 'auto',
  maxWidth: '90vw',
  height: 'auto',
  maxHeight: '90vh',
  variant: 'default',
  position: 'center',
  showHeader: true,
  showFooter: true,
  showClose: true,
  showCancel: true,
  showConfirm: true,
  cancelText: '取消',
  confirmText: '确认',
  confirmVariant: 'primary',
  confirmLoading: false,
  closeOnOverlay: true,
  closeOnEscape: true,
  lockScroll: true,
  destroyOnClose: false,
  customClass: '',
  overlayClass: '',
  bodyClass: '',
  closeAriaLabel: '关闭对话框'
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'close': []
  'cancel': []
  'confirm': []
  'opened': []
  'closed': []
}>()

// 锁定页面滚动
const { lock, unlock } = useLockScroll()

// 计算样式类
const modalClass = computed(() => [
  `apple-modal--${props.variant}`,
  `apple-modal--${props.position}`,
  {
    'apple-modal--no-header': !props.showHeader,
    'apple-modal--no-footer': !props.showFooter,
  },
  props.customClass
])

// 计算模态框样式
const modalStyle = computed(() => {
  const style: Record<string, string> = {}
  
  if (props.width !== 'auto') {
    style.width = typeof props.width === 'number' ? `${props.width}px` : props.width
  }
  if (props.maxWidth) {
    style.maxWidth = typeof props.maxWidth === 'number' ? `${props.maxWidth}px` : props.maxWidth
  }
  if (props.height !== 'auto') {
    style.height = typeof props.height === 'number' ? `${props.height}px` : props.height
  }
  if (props.maxHeight) {
    style.maxHeight = typeof props.maxHeight === 'number' ? `${props.maxHeight}px` : props.maxHeight
  }
  
  return style
})

// 事件处理
const handleClose = () => {
  emit('update:modelValue', false)
  emit('close')
}

const handleCancel = () => {
  emit('cancel')
  handleClose()
}

const handleConfirm = () => {
  emit('confirm')
}

const handleOverlayClick = () => {
  if (props.closeOnOverlay) {
    handleClose()
  }
}

const handleEscapeKey = (event: KeyboardEvent) => {
  if (event.key === 'Escape' && props.closeOnEscape && props.modelValue) {
    handleClose()
  }
}

// 监听键盘事件
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    document.addEventListener('keydown', handleEscapeKey)
    if (props.lockScroll) {
      lock()
    }
    nextTick(() => {
      emit('opened')
    })
  } else {
    document.removeEventListener('keydown', handleEscapeKey)
    if (props.lockScroll) {
      unlock()
    }
    emit('closed')
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.apple-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 16px;

  @media (max-width: 768px) {
    padding: 8px;
  }
}

.apple-modal {
  background: var(--apple-color-background-primary);
  border-radius: 12px;
  box-shadow: 
    0 25px 50px -12px rgba(0, 0, 0, 0.25),
    0 0 0 1px rgba(255, 255, 255, 0.1);
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;

  // 变体样式
  &--compact {
    min-width: 300px;
    max-width: 400px;
  }

  &--fullscreen {
    width: 100vw;
    height: 100vh;
    max-width: 100vw;
    max-height: 100vh;
    border-radius: 0;
  }

  &--drawer {
    height: 100vh;
    max-height: 100vh;
    border-radius: 12px 0 0 12px;
    margin-left: auto;
    margin-right: 0;
  }

  // 位置样式
  &--top {
    margin-top: 40px;
    margin-bottom: auto;
  }

  &--bottom {
    margin-top: auto;
    margin-bottom: 40px;
  }

  @media (max-width: 768px) {
    &--default,
    &--compact {
      width: 100%;
      max-width: calc(100vw - 16px);
      margin: 0;
    }

    &--drawer {
      width: 100%;
      height: 70vh;
      border-radius: 12px 12px 0 0;
      margin: auto 0 0 0;
    }
  }
}

.apple-modal__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px 0;
  border-bottom: 1px solid var(--apple-color-separator);
  margin-bottom: 0;
  flex-shrink: 0;

  @media (max-width: 768px) {
    padding: 16px 20px 0;
  }
}

.apple-modal__title {
  font-size: 18px;
  font-weight: 600;
  color: var(--apple-color-text-primary);
  margin: 0;
  line-height: 1.4;
  flex: 1;
}

.apple-modal__close {
  background: none;
  border: none;
  color: var(--apple-color-text-tertiary);
  cursor: pointer;
  padding: 4px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  margin-left: 16px;

  &:hover {
    background: var(--apple-color-background-secondary);
    color: var(--apple-color-text-secondary);
  }

  &:active {
    background: var(--apple-color-background-tertiary);
    transform: scale(0.95);
  }
}

.apple-modal__close-icon {
  width: 20px;
  height: 20px;
}

.apple-modal__body {
  flex: 1;
  padding: 20px 24px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--apple-color-separator);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: var(--apple-color-text-quaternary);
  }

  @media (max-width: 768px) {
    padding: 16px 20px;
  }
}

.apple-modal__footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 24px 20px;
  border-top: 1px solid var(--apple-color-separator);
  margin-top: 0;
  flex-shrink: 0;

  @media (max-width: 768px) {
    padding: 0 20px 16px;
    gap: 8px;
  }
}

// 过渡动画
.apple-modal-enter-active,
.apple-modal-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.apple-modal-enter-from,
.apple-modal-leave-to {
  opacity: 0;
}

.apple-modal-enter-from .apple-modal,
.apple-modal-leave-to .apple-modal {
  transform: scale(0.95) translateY(-20px);
}

// 暗色模式
@media (prefers-color-scheme: dark) {
  .apple-modal-overlay {
    background: rgba(0, 0, 0, 0.7);
  }

  .apple-modal {
    box-shadow: 
      0 25px 50px -12px rgba(0, 0, 0, 0.5),
      0 0 0 1px rgba(255, 255, 255, 0.05);
  }
}

// 高对比度模式
@media (prefers-contrast: high) {
  .apple-modal {
    border: 2px solid var(--apple-color-text-primary);
  }

  .apple-modal__header,
  .apple-modal__footer {
    border-color: var(--apple-color-text-primary);
  }
}

// 减少动画模式
@media (prefers-reduced-motion: reduce) {
  .apple-modal-enter-active,
  .apple-modal-leave-active {
    transition: opacity 0.2s;
  }

  .apple-modal-enter-from .apple-modal,
  .apple-modal-leave-to .apple-modal {
    transform: none;
  }
}
</style>